<template>
  <div>
    <div class="filter-header">
      <div class="float-card grid-content">
        <!--导航条-->
        <el-tabs v-model="activeName">
          <el-row justify="center" type="flex" align="middle" style="margin-bottom: 15px"
                  v-if="filterBox.largeTypeName||filterBox.subTypeName||filterBox.provinces||filterBox.city||filterBox.region">
            <el-col :span="2">
              <el-link type="info" disabled>已选条件</el-link>
            </el-col>
            <el-col :span="22">
              <el-row :gutter="4">
                <el-col :span="0.1" v-for="(value,key) in filterBox" v-if="value" :key="key">
                  <el-tag
                      closable
                      @close="handleClose(key)">
                    {{ value }}
                  </el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <el-tab-pane label="行业导航" name="industry" :lazy="true">
            <div class="filter-box">
              <el-row type="flex" align="middle" :gutter="20" justify="space-between">
                <el-col :span="2">
                  <el-link type="info" disabled>一级行业</el-link>
                </el-col>
                <el-col :span="22">
                  <el-radio-group v-model="filterBox.largeTypeName" @change="secondIndustry">
                    <el-row :gutter="4">
                      <el-col :span="0.1" v-for="item in industry" style="margin: 5px" :key="item.id">
                        <el-radio-button :label="item.name" border>
                          {{ item.name }}
                        </el-radio-button>
                      </el-col>
                      <el-col :span="0.1" style="margin: 5px">
                        <!--行业关键字转换-->
                        <el-dialog
                            title="手动添加行业关键字"
                            :visible.sync="manualInsertIndustryDlgVisible"
                            width="40%"
                            v-loading="loadingPushInfo"
                            @close="resetNavigation"
                        >
                          <el-row>
                            <el-col :span="24">
                              <el-divider content-position="left">从字符串生成(格式要求:多个主行业使用';'分开,主行业和子行业用':'分开,子行业用','分开)
                              </el-divider>
                              <el-input type="textarea" v-model="industryStr" autosize
                                        placeholder="范例:建材:鞋业,纸业,制衣;文化、体育和娱乐业:文化艺术业,新闻和出版业"></el-input>
                            </el-col>
                          </el-row>
                          <span slot="footer">
                            <el-button @click="manualInsertIndustryDlgVisible = false">取 消</el-button>
                              <el-button type="primary" @click="surePushIndustry">确 定</el-button>
                            </span>
                        </el-dialog>
                        <el-button type="info" plain @click="manualInsertIndustryDlgVisible=true">没有我想要的行业...
                        </el-button>
                      </el-col>
                    </el-row>
                  </el-radio-group>
                </el-col>
              </el-row>
              <el-divider v-if="filterBox.largeTypeName"/>
              <el-row v-if="filterBox.largeTypeName" type="flex" align="middle" :gutter="20">
                <el-col :span="2">
                  <el-link type="info" disabled>二级行业</el-link>
                </el-col>
                <el-col :span="22">
                  <el-radio-group v-model="filterBox.subTypeName">
                    <el-row :gutter="4">
                      <el-col :span="0.1" v-for="item in tempSecondIndustry" style="margin: 5px" :key="item.id">
                        <el-radio-button :label="item.name" border>
                          {{ item.name }}
                        </el-radio-button>
                      </el-col>
                    </el-row>
                  </el-radio-group>
                </el-col>
              </el-row>
            </div>
          </el-tab-pane>
          <el-tab-pane label="地区导航" name="location" :lazy="true">
            <div class="filter-box">
              <el-row type="flex" align="middle" :gutter="20">
                <el-col :span="2">
                  <el-link type="info" disabled>省份</el-link>
                </el-col>
                <el-col :span="22">
                  <el-radio-group v-model="filterBox.provinces" @change="initializeCity">
                    <el-row :gutter="4">
                      <el-col :span="0.1" v-for="item in locations" style="margin: 5px" :key="item.id">
                        <el-radio-button :label="item.name" border>
                          {{ item.name }}
                        </el-radio-button>
                      </el-col>
                    </el-row>
                  </el-radio-group>
                </el-col>
              </el-row>
              <el-divider v-if="filterBox.provinces"/>
              <el-row v-if="filterBox.provinces" type="flex" align="middle" :gutter="20">
                <el-col :span="2">
                  <el-link type="info" disabled>城市</el-link>
                </el-col>
                <el-col :span="22">
                  <el-radio-group v-model="filterBox.city" @change="initializeRegion">
                    <el-row :gutter="4">
                      <el-col :span="0.1" v-for="item in tempCity" style="margin: 5px" :key="item.id">
                        <el-radio-button :label="item.name" border>
                          {{ item.name }}
                        </el-radio-button>
                      </el-col>
                    </el-row>
                  </el-radio-group>
                </el-col>
              </el-row>
              <el-divider v-if="filterBox.city"/>
              <el-row v-if="filterBox.city" type="flex" align="middle" :gutter="20">
                <el-col :span="2">
                  <el-link type="info" disabled>地区</el-link>
                </el-col>
                <el-col :span="22">
                  <el-radio-group v-model="filterBox.region">
                    <el-row :gutter="4">
                      <el-col :span="0.1" v-for="item in tempRegion" style="margin: 5px" :key="item.id">
                        <el-radio-button :label="item.name" border>
                          {{ item.name }}
                        </el-radio-button>
                      </el-col>
                    </el-row>
                  </el-radio-group>
                </el-col>
              </el-row>
            </div>
          </el-tab-pane>
        </el-tabs>
        <!--操作条-->
        <el-divider content-position="left">操作</el-divider>
        <div id="operations">
          <div>
            <el-button type="primary" @click="filterQuery">
              聚合查询
            </el-button>
            <el-button @click="resetFilter">
              重置
            </el-button>
          </div>
          <el-alert
              title="当前总数"
              type="info"
              :closable="false"
              center
              :description="''+resultsTotal">
          </el-alert>
          <el-alert
              title="当前页数"
              type="info"
              :closable="false"
              center
              :description="''+pageCount">
          </el-alert>
          <el-button type="primary" plain @click="$router.push(`SendEmail?filterBox=${JSON.stringify(filterBox)}`)">
            直接发送
          </el-button>
          <el-switch
              v-model="detailDataVis"
              active-text="显示数据表"
              inactive-text="隐藏数据表">
          </el-switch>
        </div>
      </div>
      <div class="float-card grid-content" v-show="!uploading">
        <el-divider content-position="left">Excel数据导入</el-divider>
        <el-upload
            class="excelUpload"
            ref="xlsFileImport"
            drag
            action=""
            multiple
            accept=".xls"
            :auto-upload="false"
            :show-file-list="showUpList"
            :before-upload="beforeUploadHandler"
            :http-request="axiosUploadHandler"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">
            只能上传xls文件,大小不得超出20M
          </div>
        </el-upload>
        <el-divider content-position="left">
          <el-switch
              v-model="showUpList"
              active-text="显示列表"
              inactive-text="隐藏列表">
          </el-switch>
        </el-divider>
        <el-row :gutter="20" type="flex" justify="center" align="middle">
          <el-col :span="0.1">
            <el-button type="primary" @click="submitExcelUpload($refs.xlsFileImport.uploadFiles)">确认上传</el-button>
          </el-col>
          <el-col :span="0.1">
            <el-button type="info" @click="$refs.xlsFileImport.clearFiles();">清空列表</el-button>
          </el-col>
        </el-row>
      </div>
      <!--上传进度-->
      <div class="float-card grid-content" v-if="uploading">
        <el-divider content-position="left">上传进度</el-divider>
        <el-row type="flex" justify="center" align="middle">
          <el-col :span="0.1">
            <el-progress type="dashboard"
                         :percentage="Number(((this.uploadProgress.success + this.uploadProgress.failList.length) / this.uploadProgress.total * 100).toFixed(2))"
                         :width="150"
                         :color="uploadProgress.uploadProgressColors"></el-progress>
          </el-col>
        </el-row>
        <el-row :gutter="20" type="flex" justify="center" align="middle">
          <el-col :span="0.1">
            <el-tag
                :type="Number(((this.uploadProgress.success + this.uploadProgress.failList.length) / this.uploadProgress.total * 100).toFixed(2)) === 100?'success':'danger'">
              {{
                Number(((this.uploadProgress.success + this.uploadProgress.failList.length) / this.uploadProgress.total * 100).toFixed(2)) === 100 ? '上传完毕' : '请勿刷新页面'
              }}
            </el-tag>
          </el-col>
        </el-row>
        <el-row :gutter="20" type="flex" justify="center" align="middle">
          <el-col :span="22">
            <el-descriptions direction="vertical" :column="4" border>
              <el-descriptions-item label="成功">
                {{ uploadProgress.success }}
              </el-descriptions-item>
              <el-descriptions-item label="失败">
                {{ uploadProgress.failList.length }}
                <el-link v-if="uploadProgress.failList.length>0" type="primary"
                         @click="retryUpload">重试
                </el-link>
              </el-descriptions-item>
              <el-descriptions-item label="总数">
                {{ uploadProgress.total }}
              </el-descriptions-item>
              <el-descriptions-item label="预计结束时长(单位:秒)">
                {{ uploadProgress.ETA }}
              </el-descriptions-item>
            </el-descriptions>
          </el-col>
        </el-row>
        <el-row :gutter="20" type="flex" justify="center" align="middle">
          <el-col :span="0.1">
            <el-button type="primary" plain @click="resetUpload">
              {{
                Number(((this.uploadProgress.success + this.uploadProgress.failList.length) / this.uploadProgress.total * 100).toFixed(2)) === 100 ? '返回' : '返回并取消'
              }}
            </el-button>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="float-card grid-content" v-if="detailDataVis">
      <el-row>
        <el-col :span="24">
          <el-table
              stripe
              v-loading="loading"
              :data="customerTableData"
              tooltip-effect="light"
              height="615"
              border
          >
            <el-table-column type="expand">
              <template slot-scope="scope">
                <div style="padding-left: 60px;">
                  <el-descriptions class="margin-top" :title="scope.row.name" :column="3" border>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-user"></i>
                        代表人
                      </template>
                      {{ scope.row.representative }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-mobile-phone"></i>
                        联系电话
                      </template>
                      {{ scope.row.phone }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-location-outline"></i>
                        城市
                      </template>
                      {{ scope.row.city }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-tickets"></i>
                        注册资金
                      </template>
                      <el-tag size="small">{{ scope.row.capital ? scope.row.capital : '暂无数据' }}</el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-office-building"></i>
                        详细地址
                      </template>
                      {{ scope.row.site }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-date"></i>
                        注册日期
                      </template>
                      {{ scope.row.establishmentdate }}
                    </el-descriptions-item>
                    <el-descriptions-item :labelStyle="{width:'100px'}">
                      <template slot="label">
                        <i class="el-icon-data-analysis"></i>
                        行业描述
                      </template>
                      {{ scope.row.scope }}
                    </el-descriptions-item>
                  </el-descriptions>
                </div>
              </template>
            </el-table-column>
            <el-table-column
                label="头像"
                width="80">
              <template slot-scope="scope">
                <el-avatar> {{ scope.row.name }}</el-avatar>
              </template>
            </el-table-column>
            <el-table-column
                label="公司名"
                width="260"
                prop="name">
            </el-table-column>
            <el-table-column
                label="注册资金">
              <template slot-scope="scope">
                {{ scope.row.capital ? scope.row.capital : '暂无数据' }}
              </template>
            </el-table-column>
            <el-table-column
                label="邮箱"
                width="200"
                prop="email"
            >
            </el-table-column>
            <el-table-column
                label="代表人"
                width="80"
                prop="representative">
            </el-table-column>
            <el-table-column
                label="联系电话"
                width="130"
                prop="phone">
            </el-table-column>
            <el-table-column
                label="注册日期"
                prop="establishmentdate"
                width="130">
            </el-table-column>
            <el-table-column
                label="地址"
                prop="site">
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row type="flex" justify="center">
        <el-col :span="0.1">
          <el-pagination
              @current-change="initialInfo"
              @size-change="handleSizeChange"
              :current-page.sync="pageInfo.offset"
              layout="total, sizes,prev, pager, next, jumper"
              :page-count="pageCount"
              :pager-count="5"
              :total="resultsTotal"
              :page-sizes="[300, 600, 900]"
              :page-size="pageInfo.limit">
          </el-pagination>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import {Message} from "element-ui";
import {mapActions, mapGetters} from "vuex";

export default {
  name: "RecipientControl",
  data() {
    return {
      customerTableData: [],
      //分页信息对象
      pageInfo: {
        //当前页
        offset: 1,
        //当前页数据量
        limit: 300,
        //城市
        city: '',
        //省份
        province: '',
        //行业关键字
        scope: ''
      },
      pageCount: 0,
      resultsTotal: 0,
      loading: false,
      //控制数据表是否显示,由于数据量巨大导致渲染缓慢,性能降低,所以默认不显示
      detailDataVis: false,
      activeName: 'industry',
      filterBox: {
        largeTypeName: '',
        subTypeName: '',
        provinces: '',
        city: '',
        region: ''
      },
      //临时二级行业
      tempSecondIndustry: [],
      //临时城市
      tempCity: [],
      //临时地区
      tempRegion: [],
      //是否显示上传列表
      showUpList: false,
      //上传进度对象
      uploadProgress: {
        success: 0,
        total: 0,
        failList: [],
        uploadProgressColors: [
          {color: '#f56c6c', percentage: 20},
          {color: '#e6a23c', percentage: 40},
          {color: '#5cb87a', percentage: 60},
          {color: '#1989fa', percentage: 80},
          {color: '#6f7ad3', percentage: 100}
        ],
        //预计完成时间
        ETA: 0
      },
      uploading: false,
      uploadIndex: 0,
      //临时文件集合
      tempUpload: [],
      //当前是否为重试状态
      retry: false,
      //每个文件上传的网速
      uploadSpeed: [],
      requestConfig: {
        timeout: 20000
      },
      manualInsertIndustryDlgVisible: false,
      //从字符串中生成的数据绑定属性
      industryStr: '',
      //最后要提交给后台的对象
      pushIndustry: [],
      loadingPushInfo: false
    }
  }, mounted() {
    this.initialInfo();
    this.initializeNavigation();
  }, methods: {
    ...mapActions({
      initializeNavigation: 'navigation/initializeNavigation',
      resetNavigation: 'navigation/resetNavigation'
    }),
    //确认添加行业
    async surePushIndustry() {
      //如果是字符串形式添加,先清空,再需要对数据进行一系列的转化
      this.loadingPushInfo = true;
      if (this.industryStr) {
        this.pushIndustry = [];
        let tempStr = this.industryStr;
        //转换字符
        tempStr = tempStr.replaceAll('，', ',');
        tempStr = tempStr.replaceAll('：', ':');
        tempStr = tempStr.replaceAll('；', ';');
        //对字符串进行分割
        let mainIndustryStrArr = tempStr.split(";");
        for (let tempIndustryStr of mainIndustryStrArr) {
          //主行业
          let split = tempIndustryStr.split(":");
          //子行业
          let subIndustry = split[1].split(",");
          //子行业不比对,但必须要比对主行业,如果有重复的则不让进行添加
          for (let industryElement of this.industry) {
            if (industryElement.name === split[0]) {
              Message.warning(`>*${industryElement.name}*<已存在,无法添加!`);
              this.loadingPushInfo = false;
              return;
            }
          }
          let industry = {
            id: 0,
            name: split[0],
            subIndustry: []
          };
          let subIndustries = [];
          for (let s of subIndustry) {
            let subIndustry1 = {
              id: 0,
              name: s,
              parentId: 0
            };
            subIndustries.push(subIndustry1);
          }
          industry.subIndustry = subIndustries;
          this.pushIndustry.push(industry);
        }
      } else {
        return;
      }
      let {data: rs} = await this.axios.post('filterInfo/manualInsertIndustry', this.pushIndustry);
      Message.success("添加成功");
      this.loadingPushInfo = false;
      //关闭窗口
      this.manualInsertIndustryDlgVisible = false;
    },
    //加载表格数据
    async initialInfo() {
      this.loading = true;
      let {data: rs} = await this.axios.get(`companydata/findByPCIdLimit`, {params: this.pageInfo, timeout: 300000});
      let findByPCIdLimit = rs.content.findByPCIdLimit;
      this.customerTableData = findByPCIdLimit.list;
      this.resultsTotal = findByPCIdLimit.total;
      this.pageCount = findByPCIdLimit.pages;
      this.loading = false;
      this.$notify({
        title: '成功',
        message: '查询完毕',
        type: 'success'
      });
    },
    //分页值改变时
    handleSizeChange(val) {
      this.pageInfo.limit = val;
      this.initialInfo();
    },
    // 提醒用户查询的条件是否与预期的一致
    queryAlert() {
      this.$confirm(`此次查询将查询${this.pageInfo.city},${this.pageInfo.province},${this.pageInfo.scope}的企业`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.initialInfo();
      }).catch(() => {
        Message.warning('已取消聚合查询');
      });
    },
    //加载二级行业
    secondIndustry() {
      if (this.filterBox.largeTypeName) {
        //将之前选择的二级行业删除
        this.tempSecondIndustry = null;
        this.filterBox.subTypeName = null;
        //循环找到该对象
        for (let i = 0; i < this.industry.length; i++) {
          let temp = this.industry[i];
          if (temp.name === this.filterBox.largeTypeName) {
            this.tempSecondIndustry = temp.subIndustry;
            return;
          }
        }
      }
    },
    //加载城市
    initializeCity() {
      if (this.filterBox.provinces) {
        this.tempCity = null;
        this.filterBox.city = null;
        this.filterBox.region = null;
        for (let i = 0; i < this.locations.length; i++) {
          let temp = this.locations[i];
          if (temp.name === this.filterBox.provinces) {
            this.tempCity = temp.city;
            return;
          }
        }
      }
    },
    //加载地区
    initializeRegion() {
      if (this.filterBox.city) {
        this.tempRegion = null;
        this.filterBox.region = null;
        for (let i = 0; i < this.locations.length; i++) {
          let temp = this.locations[i];
          for (let j = 0; j < temp.city.length; j++) {
            if (temp.city[j].name === this.filterBox.city) {
              this.tempRegion = temp.city[j].region;
              return;
            }
          }
        }
      }
    },
    //过滤盒关闭单个标签时 需要阶级删除,上层删除,下层也需要删除
    handleClose(key) {
      //如果是上层被删除,那么相应的下层也应该删除
      let tempKeys = [key];
      if (key === 'largeTypeName') {
        tempKeys.push('subTypeName');
        this.pageInfo.scope = '';
      }
      //删除省份
      if (key === 'provinces') {
        tempKeys.push('city', 'region');
        this.pageInfo.city = '';
        this.pageInfo.province = '';
      }
      //城市被删除
      if (key === 'city') {
        tempKeys.push('region');
        this.pageInfo.city = '';
      }
      for (let i = 0; i < tempKeys.length; i++) {
        this.filterBox[tempKeys[i]] = null;
      }
    },
    //重置过滤条件
    resetFilter() {
      this.handleClose('largeTypeName');
      this.handleClose('provinces');
      this.activeName = "industry";
      this.pageInfo.city = '';
      this.pageInfo.province = '';
      this.pageInfo.scope = '';
      if (this.initialInfo()) {
        this.$notify({
          title: '成功',
          message: '重置完毕',
          type: 'success'
        });
      }
    },
    //聚合查询
    filterQuery() {
      //获取地区信息
      //将市字符去除
      if (this.filterBox.city) {
        if (this.filterBox.city.indexOf("市") > 0) {
          this.pageInfo.city = this.filterBox.city.substring(0, this.filterBox.city.indexOf("市"));
        } else {
          this.pageInfo.city = this.filterBox.city;
        }
      } else {
        this.pageInfo.city = "";
      }
      if (this.filterBox.provinces) {
        if (this.filterBox.provinces.indexOf("市") > 0) {
          this.pageInfo.province = this.filterBox.provinces.substring(0, this.filterBox.provinces.indexOf("市"));
        } else {
          this.pageInfo.province = this.filterBox.provinces;
        }
      }
      //获取行业信息
      //如果附属行业没有,那就选择主行业作为过滤条件
      if (this.filterBox.subTypeName) {
        this.pageInfo.scope = this.filterBox.subTypeName;
      } else {
        this.pageInfo.scope = this.filterBox.largeTypeName;
      }
      this.initialInfo();
    },
    //手动上传
    submitExcelUpload(fileList) {
      this.$confirm('是否确认上传?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tempUpload = fileList;
        if (this.tempUpload.length === 0) {
          Message.warning('请选择表格文件!');
          return false;
        }
        //先将上传集合清空
        this.$refs.xlsFileImport.clearFiles();
        this.showUpList = false;
        this.uploading = true;
        //将上一次上传结果清空
        this.uploadProgress.success = 0;
        this.uploadProgress.total = this.tempUpload.length;
        this.uploadProgress.failList.length = 0;
        this.uploadProgress.ETA = 0;
        this.uploadSpeed = [];
        if (this.retry) {
          //重试将请求超时时长设置为40s
          this.requestConfig.timeout = 40000;
        }
        //递归上传
        this.uploadDig(this.tempUpload);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消上传'
        });
      });
    },
    //递归上传文件
    uploadDig() {
      if (this.uploadIndex < this.tempUpload.length) {
        if (this.retry) {
          this.uploadHandler(this.tempUpload[this.uploadIndex]);
        } else {
          this.$refs.xlsFileImport.uploadFiles[0] = this.tempUpload[this.uploadIndex];
          this.$refs.xlsFileImport.submit();
        }
      } else {
        this.uploadIndex = 0;
        this.$refs.xlsFileImport.clearFiles();
        this.tempUpload = [];
        this.uploadSpeed = [];
        this.retry = false;
        this.initialInfo();
        console.log(`%c 全部数据导入完毕 %c 失败数量: %c ${this.uploadProgress.failList.length} %c 成功数量: %c ${this.uploadProgress.success}`, 'font-size:18px;color:#2EFF7', 'color:#FFFF00', 'color:#FFFF00', 'color:#00FF00', 'color:#00FF00');
      }
    },
    //重置上传数据
    resetUpload() {
      this.uploading = false;
      this.tempUpload = [];
      this.uploadIndex = 0;
      this.$refs.xlsFileImport.clearFiles();
      this.$refs.xlsFileImport.abort();
      this.retry = false;
    },
    //上传前先判断文件格式是否正确
    beforeUploadHandler(file) {
      if (file.name.substring(file.name.lastIndexOf('.'), file.name.length) !== '.xls') {
        Message.warning(file.name + '的文件不符合要求!,请重新上传');
        return false;
      }
      return true;
    },
    //自定义上传
    axiosUploadHandler(params) {
      //文件上传对象触发submit时调用
      const file = params.file,
          fileType = file.type,
          isXls = fileType.indexOf("ms-excel") > 0,
          isLt20M = file.size / 1024 / 1024 < 20;
      if (!isXls) {
        this.$message.warning("只能上传格式为xls的表格文件!");
        return;
      }
      if (!isLt20M) {
        this.$message.warning("文件大小不得超出20M!");
        return;
      }
      this.uploadHandler(file);
    },
    //上传函数
    uploadHandler(file) {
      // 根据后台需求数据格式
      const form = new FormData();
      //文件对象
      form.append("file", file);
      // 项目封装的请求方法，下面做简单介绍
      // 上传表格
      this.axios.post('excelUpload/fileUpload', form, {
        headers: {"content-type": "multipart/form-data"},
        timeout: this.requestConfig.timeout,
        'request-startTime': new Date().getTime()
      }).then((response) => {
        let excelUploadRequestDuration = ((new Date().getTime() - response.config['request-startTime']) / 1000).toFixed(2);
        //导入数据 自动选择工作表1进行数据导入 !
        this.axios.post(`excelUpload/getSheetName/${response.data.content.sheetNames[0]}`, null, {
          timeout: this.requestConfig.timeout,
          'request-startTime': new Date().getTime()
        }).then((worksheetResponse) => {
          let worksheetRequestDuration = ((new Date().getTime() - worksheetResponse.config['request-startTime']) / 1000).toFixed(2);
          //该请求总耗时
          let totalRequestDuration = excelUploadRequestDuration + worksheetRequestDuration;
          //传输的耗时与上传的文件大小有关  可通过文件大小和当前的网速来估算请求的时间  当前网速由文件大小和响应时间来进行计算
          let formatTime = totalRequestDuration.toString().substring(0, totalRequestDuration.toString().lastIndexOf('.'));
          //当前网速
          let speed = (file.size / 1024) / ((formatTime * 1000) / 1024);
          //计算剩余时间
          let cupSpeed = this.cupSpeed(speed);
          console.log(`%c 平均网速:${cupSpeed.avgSpeed}/s 剩余大小:${cupSpeed.remainingSize / 1024}m 预计结束时长:${this.uploadProgress.ETA} \n %c 已上传并导入成功 %c ${file.name} %c 耗时${totalRequestDuration} %c 文件大小:${file.size / 1024 / 1024}M %c 当前网速:${speed}kb/s`, 'color:#f07810', 'color:#08ffc8', 'color:#1ee3cf;', 'background:#0d3f67;color:#f2f4f6', 'color:#6b48ff', 'color:#1687a7');
          this.uploadProgress.success++;
        }).catch((err) => {
          console.error(`%c ${file.name} %c 工作表数据导入异常 %c ${err}`, 'color:#FFFFFF;background:#FF0000', 'color:#FF4000', 'color:#FF0000;background:#BDBDBD');
          this.cupSpeed(0);
          this.uploadProgress.failList.push(file);
        }).finally(() => {
          this.uploadIndex++;
          this.uploadDig();
        });
      }).catch((err) => {
        console.error(`%c ${file.name} %c 表格上传异常 %c ${err}`, 'color:#FFFFFF;background:#FF0000', 'color:#FF4000', 'color:#FF0000;background:#BDBDBD');
        this.uploadProgress.failList.push(file);
        this.cupSpeed(0);
        //如果出现了异常
        this.uploadIndex++;
        this.uploadDig();
      });
    },
    //重试上传
    retryUpload() {
      this.retry = true;
      let tempList = [];
      for (let i = 0; i < this.uploadProgress.failList.length; i++) {
        tempList.push(this.uploadProgress.failList[i]);
      }
      this.submitExcelUpload(tempList);
    },
    //网络测速
    cupSpeed(speed) {
      //计算平均网速
      this.uploadSpeed.push(speed);
      let totalSpeed = 0;
      for (let i = 0; i < this.uploadSpeed.length; i++) {
        totalSpeed += this.uploadSpeed[i];
      }
      let avgSpeed = totalSpeed / this.uploadSpeed.length;
      //获得剩余的文件大小
      let remainingSize = 0;
      for (let i = this.uploadIndex + 1; i < this.tempUpload.length; i++) {
        remainingSize += this.tempUpload[i].size / 1024;
      }
      //剩余大小/每秒网速
      this.uploadProgress.ETA = (remainingSize / avgSpeed * 10).toFixed(2);
      return {avgSpeed, remainingSize};
    }
  }, computed: {
    ...mapGetters({industry: 'navigation/getIndustry', locations: 'navigation/getLocations'})
  }
}
</script>

<style scoped>
.filter-header {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
}

.filter-header > .grid-content:first-child {
  width: 65vw;
}

.filter-header > .grid-content:last-child {
  width: 24vw;
}

.grid-content {
  padding: 10px;
}

.filter-header + .float-card {
  margin-top: 10px;
}

.el-cascader {
  width: 100%;
}

.el-alert {
  margin-bottom: 10px;
}


/*过滤盒子*/
.filter-box {
  border-radius: 4px;
  height: 200px;
  overflow-x: hidden;
  padding: 10px;
  border: 1px solid #dcdfe6;
}

.excelUpload {
  text-align: center;
  overflow: scroll;
  overflow-x: hidden;
  height: 275px;
}

.filter-header > .grid-content:last-child {
  min-height: 450px;
}

.filter-header + .grid-content {
  min-height: 700px;
}

#operations {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-around;
  align-items: center;
}

#operations > .el-alert {
  width: auto;
}

@media screen and (max-width: 1440px) {
  .filter-header {
    flex-flow: column wrap;
    align-items: center;
  }

  .filter-header > .grid-content:first-child, .filter-header > .grid-content:last-child {
    width: 98%;
  }

  .grid-content + .grid-content {
    margin-top: 10px;
  }
}

@media screen and (max-width: 570px) {
  #operations {
    flex-flow: column wrap;
    align-items: center;
    justify-content: space-around;
    height: 400px;
  }

  #operations > div:first-child {
    display: flex;
    flex-flow: row nowrap;
    width: 90%;
  }

  #operations > div:first-child > .el-button:first-child {
    flex: 2;
  }

  #operations > div:first-child > .el-button:last-child {
    flex: 1;
  }

  #operations > .el-alert, #operations > .el-button {
    width: 90%;
    margin: 0;
  }

  #operations > button:first-child {
    margin: 0;
  }

  .grid-content .el-pagination > span {
    background: #409EFF;
    margin: 0;
    padding: 0;
  }

  .grid-content .el-pagination {
    display: flex;
    flex-flow: column wrap;
    align-items: center;
    justify-content: space-around;
    height: 400px;
  }
}
</style>